package dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateDao<E> {
	private static Configuration configuration = null;
	private static ServiceRegistry serviceRegistry = null;
	private static SessionFactory sessionFactory = null;
	
	private Class<E> classe;
	
	public HibernateDao(Class<E> classe) {
		this();
		this.classe = classe;
	}
	
	private HibernateDao() {
		if (configuration == null){
			configuration = new Configuration();
			configuration.configure();			
		}
		if (serviceRegistry == null){
			serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
		}
        if (sessionFactory == null) {
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        }
	}
	public Session getSession(){
		return sessionFactory.openSession();
	}

	@SuppressWarnings("unchecked")
	public List<E> listagem() throws Exception {
		// TODO Auto-generated method stub		
		Session session = getSession();
		try{
			org.hibernate.Query query = session.createQuery("From " + this.classe.getSimpleName());
			return query.list();
		}catch(Exception ex){
			throw ex;
		}finally{
			session.close();
		}	
	}	
	
	@SuppressWarnings("unchecked")
	public E getById(Long id) throws Exception{
		Session session = getSession();
		try{
			return (E) session.get(this.classe, id);			
		}catch(Exception ex){
			throw ex;
		}finally{
			session.close();
		}		
	}
	
	
}
